package dbinit

import (
	"fmt"
	"gorm.io/gorm"
	"server/application/constant/keys"
	"server/pkg/configs"
	"server/setting"
)

var db *gorm.DB

// GetDbInstance 获取gorm示例的副本
func GetDbInstance() *gorm.DB {
	//返回数据库实例的副本
	copyDb := *db
	return &copyDb
}

func InitDb() {
	initMysql(
		configs.GetConf().GetString(keys.ConfigKeyMysqlIp),
		configs.GetConf().GetString(keys.ConfigKeyMysqlPort),
		configs.GetConf().GetString(keys.ConfigKeyMysqlUser),
		configs.GetConf().GetString(keys.ConfigKeyMysqlDb),
		configs.GetConf().GetString(keys.ConfigKeyMysqlPwd),
	)
	//迁移表
	if GetDbInstance() != nil {
		//自动迁移表结构
		err := db.AutoMigrate(setting.EntityAutoMigrateList...)
		if err != nil {
			fmt.Println("迁移表结构失败" + err.Error())
			panic(err)
		}
	}
}
